export default class AHP {
  constructor(matrix) {
    if (!matrix.every((row) => row.length === matrix.length)) {
      throw new Error("Matrix must be square");
    }
    this.matrix = matrix; // matrix为判断矩阵
    this.n = matrix.length; // 表示为矩阵的阶数
    this.riMap = {
      // Random Consistency Index (RI) 标准值,一般不超过10个元素，如果超过会考虑构建二级指标
      1: 0,
      2: 0,
      3: 0.58,
      4: 0.9,
      5: 1.12,
      6: 1.24,
      7: 1.32,
      8: 1.41,
      9: 1.45,
      10: 1.49,
    };
  }

  // 计算权重（几何平均法 ，方根法）
  calculateWeights() {
    const n = this.n;
    const geoMeans = this.matrix.map((row) => {
      const product = row.reduce((acc, val) => acc * val, 1); // 计算每一行的乘积
      return Math.pow(product, 1 / n); // 每一行相乘并做其n次方根
    });

    const sum = geoMeans.reduce((a, b) => a + b, 0); // 计算几何平均值的和
    return geoMeans.map((mean) => mean / sum); // 归一化，每个除以总数，即为每个的权重
  }

  // 计算一致性比率
  calculateConsistency(weights) {
    const n = this.n;

    // 计算加权求和向量 Aw
    const aw = this.matrix.map((row) =>
      row.reduce((sum, aij, j) => sum + aij * weights[j], 0)
    );

    // 计算最大特征值 λmax
    const lambdaSum = aw.reduce((sum, awi, i) => sum + awi / weights[i], 0);
    const lambdaMax = lambdaSum / n; // 计算 λmax的公式 为 λmax = 求和(Aw)/nw

    // 计算一致性指标 CI
    const ci = (lambdaMax - n) / (n - 1); // 计算一致性指标 CI = (λmax - n) / (n - 1)

    // 获取随机一致性指标 RI
    const ri = this.riMap[n] || 0;

    // 计算一致性比率 CR
    const cr = ri === 0 ? 0 : ci / ri; // CR = CI / RI

    return {
      lambdaMax: lambdaMax,
      ci: ci,
      cr: cr,
      isConsistent: cr < 0.1, // CR < 0.1 表示一致性可接受
    };
  }

  // 执行完整分析
  analyze() {
    try {
      const weights = this.calculateWeights();
      const consistency = this.calculateConsistency(weights);

      return {
        weights: weights.map((w) => Number(w.toFixed(4))),
        ...consistency,
        cr: Number(consistency.cr.toFixed(4)),
      };
    } catch (error) {
      return { error: error.message };
    }
  }
}

// 示例用法
// const matrix = [
//   [1, 3, 5],
//   [1/3, 1, 2],
//   [1/5, 1/2, 1]
// ];

// const ahp = new AHP(matrix);
// const result = ahp.analyze();
// console.log('权重:', result.weights);
// console.log('CR:', result.cr);
// console.log('一致性检验:', result.isConsistent ? '通过' : '未通过');
